package cn.ycc1.boot3video.video;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class FfmpegHlsGenerator {

    /**
     * 使用FFmpeg生成多清晰度的HLS流
     */
    public static boolean generateMultiQualityHls(String inputVideoPath, String outputDir) {
        try {
            // FFmpeg命令生成多个清晰度
            String[] commands = {
                    "ffmpeg", "-i", inputVideoPath,
                    // 1080p
                    "-map", "0:v:0", "-map", "0:a:0",
                    "-c:v", "libx264", "-c:a", "aac",
                    "-b:v", "2000k", "-maxrate", "2140k", "-bufsize", "3000k",
                    "-b:a", "128k", "-vf", "scale=1920:1080",
                    "-hls_time", "4", "-hls_playlist_type", "vod",
                    "-hls_segment_filename", outputDir + "/1080p_%03d.ts",
                    outputDir + "/1080p.m3u8",

                    // 720p
                    "-map", "0:v:0", "-map", "0:a:0",
                    "-c:v", "libx264", "-c:a", "aac",
                    "-b:v", "1000k", "-maxrate", "1070k", "-bufsize", "1500k",
                    "-b:a", "96k", "-vf", "scale=1280:720",
                    "-hls_time", "4", "-hls_playlist_type", "vod",
                    "-hls_segment_filename", outputDir + "/720p_%03d.ts",
                    outputDir + "/720p.m3u8",

                    // 480p
                    "-map", "0:v:0", "-map", "0:a:0",
                    "-c:v", "libx264", "-c:a", "aac",
                    "-b:v", "500k", "-maxrate", "535k", "-bufsize", "750k",
                    "-b:a", "64k", "-vf", "scale=854:480",
                    "-hls_time", "4", "-hls_playlist_type", "vod",
                    "-hls_segment_filename", outputDir + "/480p_%03d.ts",
                    outputDir + "/480p.m3u8"
            };

            Process process = Runtime.getRuntime().exec(commands);

            // 读取FFmpeg输出
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getErrorStream())
            );

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("FFmpeg: " + line);
            }

            int exitCode = process.waitFor();
            return exitCode == 0;

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}
